<?php
namespace App\Services\Admin;

use App\Models\AdminModel;
use App\Services\BaseService;

/**
 * 后台管理员服务
 */
class AdminService extends BaseService
{
    /**
     * 管理员添加编辑
     * $param 参数
     * @return array
     */
    public static function editAdmin($data = [])
    {
        try {
            AdminModel::startTrans();
            $data['update_time'] = time();
            if(!empty($data['id'])){
                $id = $data['id'];
                unset($data['id']);
                if($data['password']){
                    $pass = checkPassword($data['password']);
                    if($pass['code'] != 200) {
                        return AdminModel::result("", 500, $pass['msg']);
                    }
                    $data['password'] = password_hash($data['password'],PASSWORD_DEFAULT);
                }else{
                    unset($data['password']);
                }
                $data['update_time'] = time();
                $res = AdminModel::where('id',$id)->update($data);
            }else{
                $check = AdminModel::where("account", $data['account'])->count();
                if($check != 0) {
                    return AdminModel::result("", 500, "已存在 {$data['account']} 账号，请更换");
                }
//                $pass = checkPassword($data['password']);
//                if($pass['code'] != 200) {
//                    return AdminModel::result("", 500, $pass['msg']);
//                }
                $data['create_time'] = time();
                $data['password'] = password_hash($data['password'],PASSWORD_DEFAULT);
                $data['unique'] = uniqid();
                $data['update_time'] = time();
                $res = AdminModel::create($data);
            }
            if($res) {
                AdminModel::commit();
                return AdminModel::result("", 200, "操作成功");
            }
            return AdminModel::result("", 500, "操作失败");

        } catch (\Exception $e) {
            AdminModel::rollback();
            return AdminModel::result("", 500, $e->getMessage());
        }
    }

    /**
     * 管理员删除
     * $param 参数
     * @return array
     */
    public static function delAdmin($ids){
        try{
            AdminModel::startTrans();

            $res = AdminModel::destroy($ids);

            if($res) {
                AdminModel::commit();
                return AdminModel::result("", 200, "操作成功");
            }
            return AdminModel::result("", 500, "操作失败");

        }catch (\Exception $e){
            AdminModel::rollback();
            return AdminModel::result("", 500, $e->getMessage());
        }
    }

}
